package com.alogic.xscript.plugins;

import java.io.*;

import org.apache.commons.lang3.StringUtils;
import com.alogic.xscript.AbstractLogiclet;
import com.alogic.xscript.ExecuteWatcher;
import com.alogic.xscript.Logiclet;
import com.alogic.xscript.LogicletContext;
import com.alogic.xscript.doc.XsObject;
import com.anysoft.util.IOTools;
import com.anysoft.util.Properties;
import com.anysoft.util.PropertiesConstants;
import com.anysoft.util.Settings;
import com.anysoft.util.resource.ResourceFactory;

/**
 * 从文件中装载内容
 * 
 * @author yyduan
 *
 * @version 1.6.13.23 [20201030 duanyy] <br>
 * - 优化xscript的日志机制  <br>
 *
 * @version 1.6.15.4 [20211112 duanyy] <br>
 * - 修复bug <br>
 */
public class Load extends AbstractLogiclet{
	protected String $src = "";
	protected String $secondary = "";
	protected String $dft = "";
	protected String id;
	protected String encoding;
	protected int bufferSize = 1024;
	
	public Load(String tag, Logiclet p) {
		super(tag, p);
	}

	@Override
	public void configure(Properties p){
		super.configure(p);
		
		$src = PropertiesConstants.getRaw(p,"src",$src);
		$secondary = PropertiesConstants.getRaw(p,"secondary",$secondary);
		$dft = PropertiesConstants.getRaw(p,"dft",$dft);
		id = PropertiesConstants.getRaw(p,"id","$" + this.getXmlTag());
		encoding = PropertiesConstants.getString(p,"encoding",
				PropertiesConstants.getString(p,"http.encoding","utf-8",false),true);
		bufferSize = PropertiesConstants.getInt(p,"bufSize",bufferSize,true);
		bufferSize = bufferSize <= 0? 1024:bufferSize;
	}
		
	@Override
	protected void onExecute(XsObject root,XsObject current,LogicletContext ctx, ExecuteWatcher watcher) {
		String src = PropertiesConstants.transform(ctx, $src, "");
		String secondary = PropertiesConstants.transform(ctx, $secondary, "");
		String dft = PropertiesConstants.transform(ctx, $dft, "");
		
		String content = loadContent(src,secondary,dft);
		if (StringUtils.isNotEmpty(id)){
			ctx.SetValue(id, content);
		}
	}	
	
	protected String loadContent(String src, String secondary, String dft) {
		ResourceFactory resourceFactory = Settings.getResourceFactory();
		InputStream in = null;
		try {
			in = resourceFactory.load(src, secondary);
			byte[] data = readBytes(in,bufferSize);
			return new String(data,encoding);
		} catch (Exception ex) {
			log("The config file is not a valid file,url = " + src,LOG_ERROR);
			return dft;
		} finally {
			IOTools.close(in);
		}
	}

	public static byte [] readBytes(InputStream in,int bufferSize) throws IOException {
		ByteArrayOutputStream bos = new ByteArrayOutputStream(bufferSize*4);
		byte[] buf =new byte[bufferSize];
		int size=0;
		while((size=in.read(buf))!=-1)
		{
			bos.write(buf,0,size);
		}
		return bos.toByteArray();
	}
}
